package com.lyf.boot.modules.system.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import com.lyf.boot.base.system.entity.SysDept;
import com.lyf.boot.constant.Constant;
import com.lyf.boot.core.model.CascadeVo;
import com.lyf.boot.modules.system.dao.SysDeptDao;
import com.lyf.boot.modules.system.entity.dto.SysDeptDto;
import com.lyf.boot.modules.system.entity.vo.SysDeptVo;
import com.lyf.boot.modules.system.service.ISysDeptService;
import com.lyf.boot.utils.MapstructUtil;
import com.lyf.boot.utils.TreeUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author Luyufan
 * @date 2023/7/7 10:40
 */
@Service
@RequiredArgsConstructor
public class SysDeptServiceImpl implements ISysDeptService {

    private final SysDeptDao sysDeptDao;

    @Override
    public List<SysDeptVo> getSysDeptList() {
        List<SysDeptVo> list = sysDeptDao.selectSysDeptList();
        //return list;
        String idName = "deptId";
        return TreeUtil.buildTree(list, Constant.TREE_PARENT_ID, idName, Constant.PARENT_ID_NAME, Constant.CHILDREN_NAME);
    }

    @Override
    public List<CascadeVo> getDeptCascade() {
        List<SysDeptVo> list = getSysDeptList();
        return MapstructUtil.convert(list, CascadeVo.class);
    }

    @Override
    public SysDeptVo getSysDeptInfo(Long deptId) {
        return sysDeptDao.selectSysDeptById(deptId);
    }

    @Override
    public void saveSysDept(SysDeptDto dto) {
        dto.setParentId(ObjectUtil.defaultIfNull(dto.getParentId(), Constant.TREE_PARENT_ID));
        SysDept sysDept = MapstructUtil.convert(dto, SysDept.class);
        sysDeptDao.insert(sysDept);
    }

    @Override
    public void updateSysDept(SysDeptDto dto) {
        SysDept sysDeptDb = sysDeptDao.selectById(dto.getDeptId());
        Assert.notNull(sysDeptDb, "部门不存在");
        dto.setParentId(ObjectUtil.defaultIfNull(dto.getParentId(), Constant.TREE_PARENT_ID));
        SysDept sysDept = MapstructUtil.convert(dto, SysDept.class);
        sysDeptDao.updateById(sysDept);
    }

    @Override
    public void deleteSysDept(List<Long> ids) {
        //TODO 判断下级部门
        sysDeptDao.deleteByIds(ids);
    }
}
